package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConexaoDAO {

    //private static Connection conn;
    public static Connection getConnection() throws SQLException {
        Connection conn = null;
        if ((conn != null)
                && (!conn.isClosed())) {
            return conn;
        } else {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(ConexaoDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
            conn = null;
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/inspecaoclaro","root","root");
            conn.setAutoCommit(false);
            return conn;

            /*InitialContext ctx = null;
            DataSource db = null;
            try {
            ctx = new InitialContext();
            db = (DataSource) ctx.lookup("java:comp/env/jdbc/inspecao");
            conn = db.getConnection();
            } catch (Exception ex) {
            Logger.getLogger(ConexaoDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
            return conn;*/
        }
    }

    public static void desconecta(Connection conn, ResultSet res, PreparedStatement pstmt) {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
            if (res != null) {
                res.close();
            }
            if (conn != null) {
                conn.close();
            }
            conn = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            System.out.println(getConnection());
            System.out.println(getConnection());
            System.out.println(getConnection());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
